package cn.intotw.rdcj.admin.shiro;

import cn.intotw.rdcj.admin.domain.dao.RolesResourceDao;
import cn.intotw.rdcj.admin.domain.dao.RolesUserDao;
import cn.intotw.rdcj.admin.domain.dao.UserBaseDao;
import cn.intotw.rdcj.admin.domain.po.UserBase;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


public class RdcjAdminRealm extends AuthorizingRealm {
    @Autowired
    RolesUserDao rolesUserDao;
    @Autowired
    UserBaseDao userBaseDao;
    @Autowired
    RolesResourceDao rolesResourceDao;
    private final static String SUPER_ADMIN="superAdmin";
    public final static String authorizationCacheKey="rdcj:shiro_authorization_cache";
    public final static String authenticationCacheKey="rdcj:shiro_authentication_cache:";
    @Override
    public String getName() {
        return "rdcjAdminRealm";
    }

    public RdcjAdminRealm(CacheManager cacheManager, RolesUserDao rolesUserDao, UserBaseDao userBaseDao, RolesResourceDao rolesResourceDao) {
        super(cacheManager);
        this.setAuthenticationCacheName(authorizationCacheKey);
        this.setAuthorizationCacheName(authenticationCacheKey);
        this.rolesUserDao = rolesUserDao;
        this.userBaseDao = userBaseDao;
        this.rolesResourceDao = rolesResourceDao;
    }


    /**
        授权
     * @author Chenxiang
     * @date 2021/6/2 14:16
     * @param principalCollection
     * @return org.apache.shiro.authz.AuthorizationInfo
     * @see PrincipalCollection
     * @see AuthorizationInfo
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Object username = principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(getRoles(username.toString()));
        simpleAuthorizationInfo.setStringPermissions(getPermissons(username.toString()));
        return simpleAuthorizationInfo;
    }
    /**
      重写hasRole方法判断权限，让管理员拥有所有权限
    */
    @Override
    protected boolean hasRole(String roleIdentifier, AuthorizationInfo info) {
        if(isSuperAdmin(info.getRoles())){
            return true;
        }else {
            return super.hasRole(roleIdentifier, info);
        }
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName());
    }

    /**
     * 查询数据库，获取用户的角色
     *
     * @param username
     * @return
     */
    private Set<String> getRoles(String username) {
        QueryWrapper<UserBase> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",username);
        final UserBase userBase = userBaseDao.selectOne(wrapper);
        final List<String> strings = rolesUserDao.selectRolesByUserId(userBase.getUserId());
        return new HashSet<>(strings);
    }
    /**
     * 查询数据库，获取用户的权限
     *
     * @param username
     * @return
     */
    private Set<String> getPermissons(String username) {
        QueryWrapper<UserBase> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",username);
        final UserBase userBase = userBaseDao.selectOne(wrapper);
        final List<String> strings = rolesResourceDao.selectPermissionByUserId(userBase.getUserId());
        return new HashSet<>(strings);
    }
    /**
      判断是否超级管理员
    */
    private boolean isSuperAdmin(Collection<String> role){
        if(!CollectionUtils.isEmpty(role)){
            return role.contains(SUPER_ADMIN);
        }else {
            return false;
        }
    }
}